﻿using System;
using System.IO;
using System.Text;
using Al_FrameWork;
using Editor;
using UnityEditor;
using UnityEngine;

/// <summary>
/// PrintFolderInFileName
/// </summary>
public class CreateLuaPopup : EditorWindow
{
    private static string dirPath;
    private static string str = "请输入lua.txt文件名";
    private static string asssetFileName = "Assets";
    private static string basePath;

    [MenuItem("Assets/Create/Lua", false, 1)]
    private static void CreateLua()
    {
        string[] strs = Selection.assetGUIDs;
        dirPath = AssetDatabase.GUIDToAssetPath(strs[0]);
        int totalLen = Application.dataPath.Length;
        basePath = Application.dataPath.Substring(0, totalLen - asssetFileName.Length);
        var window = GetWindow<CreateLuaPopup>();
        window.Show();
    }

    private void OnGUI()
    {
        GUILayout.Label("Base Settings", EditorStyles.boldLabel);
        str = EditorGUILayout.TextField("Text Field", str);
        if (GUILayout.Button("创建"))
        {
            if (string.IsNullOrEmpty(str) || string.IsNullOrWhiteSpace(str))
            {
                return;
            }

            if (str.Equals("请输入lua.txt文件名"))
            {
                return;
            }
            
            string filePath = basePath + dirPath + "/" + str + ".lua.txt";
            try
            {
                FileStream fileStream = File.Create(filePath);
                string content = ABPackConfig.luaTemplate;
                byte[] bytes = Encoding.UTF8.GetBytes(content);
                fileStream.Write(bytes, 0, bytes.Length);
                fileStream.Close();
                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                GlobalFunctions.Err("创建文件{0}异常", e.Message);
            }
            finally
            {
                Close();
            }
        }
    }
}